package win.wellcoding.wechat.tuling;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.log4j.Logger;

import org.json.JSONException;
import org.json.JSONObject;

public class TulingApiProcess {

	private static Logger logger 		= Logger.getLogger(TulingApiProcess.class);

	public final int CONNECT_TIMEOUT 	= 5 * 1000;
	public final int READ_TIMEOUT 	= 5 * 1000;

	/**
	 * 调用图灵机器人api接口，获取智能回复内容，解析获取自己所需结果
	 * 
	 * @param content
	 * @return
	 * @throws IOException
	 */
	public String getTulingResult(String content) throws IOException {
		/** 此处为图灵api接口，参数key需要自己去注册申请 */
		String apiUrl = "http://www.tuling123.com/openapi/api?key=287775c71b6b3b128c2f6640543f7367&info=";
		String param = "";
		try {
			param = apiUrl + URLEncoder.encode(content, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} // 将参数转为url编码

		/** 发送httpget请求 */

		String result = getRequest(param);

		/** 请求失败处理 */
		if (null == result) {
			return "对不起，你说的话真是太高深了……";
		}

		try {
			JSONObject json = new JSONObject(result);
			// 以code=100000为例，参考图灵机器人api文档
			if (100000 == json.getInt("code")) {
				result = json.getString("text");
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}

	public String getRequest(String urlParam) throws IOException {
		StringBuffer resultBuffer = new StringBuffer();
		HttpURLConnection conn = null;
		BufferedReader in = null;
		try {
			URL url = new URL(urlParam);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setConnectTimeout(CONNECT_TIMEOUT);
			conn.setReadTimeout(READ_TIMEOUT);
			conn.connect();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line = "";
			while ((line = in.readLine()) != null) {
				resultBuffer.append(line);
			}
		} finally {
			try {
				if (null != in) {
					in.close();
					in = null;
				}
				if (null != conn) {
					conn.disconnect();
					conn = null;
				}
			} catch (IOException e) {
				logger.error("colse connect failure! ", e);
			}
		}
		return resultBuffer.toString();
	}
}
